package com.sls.web.manager.sys.service.impl;

import java.util.List;
import java.util.UUID;

import org.springframework.stereotype.Service;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.sls.core.common.CommonUtil;
import com.sls.core.socket.Head;
import com.sls.core.socket.SocketDTO;
import com.sls.web.manager.common.Constants;
import com.sls.web.manager.page.Pagination;
import com.sls.web.manager.pojo.UserInfoVO;
import com.sls.web.manager.socket.SuperService;
import com.sls.web.manager.sys.pojo.Permission;
import com.sls.web.manager.sys.pojo.RolePermission;
import com.sls.web.manager.sys.service.RolePermissionService;

@Service("rolePermissionService")
public class RolePermissionServiceImpl extends SuperService implements
		RolePermissionService {

	@Override
	public Pagination<RolePermission> querRolepermission(RolePermission rp,
			UserInfoVO userinfo) throws Exception {
		Gson gson = CommonUtil.gson();
		Head head = new Head();
		head.setRequestId(UUID.randomUUID().toString());
		head.setServiceCode(Constants.ROLE_PERMISSION_PAGE);
		head.setIp(userinfo.getCurrentIp());
		head.setUserId(userinfo.getUserId());
		SocketDTO dto = super.send(head, rp);
		Head rHead = dto.getHead();
		String body = dto.getBody();
		if (Constants.SUCCESS.equals(rHead.getResponseCode())) {
			Pagination<RolePermission> role = gson.fromJson(body,
					new TypeToken<Pagination<RolePermission>>() {
					}.getType());
			return role;
		}
		return null;
	}

	@Override
	public List<Permission> queryRolepermissionByRoleId(String roleId,
			UserInfoVO userinfo) throws Exception {
		Gson gson = CommonUtil.gson();
		Head head = new Head();
		head.setRequestId(UUID.randomUUID().toString());
		head.setServiceCode(Constants.FIND_RP_BY_ROLEID);
		head.setIp(userinfo.getCurrentIp());
		head.setUserId(userinfo.getUserId());
		RolePermission r = new RolePermission();
		r.setRoleId(roleId);
		SocketDTO dto = super.send(head, r);
		Head rHead = dto.getHead();
		String body = dto.getBody();
		if (Constants.SUCCESS.equals(rHead.getResponseCode())) {
			List<Permission> list = gson.fromJson(body,
					new TypeToken<List<Permission>>() {
					}.getType());
			return list;
		}
		return null;
	}

	@Override
	public boolean updateRPByRoleId(List<String> codes, String roleId,
			UserInfoVO userinfo) throws Exception {
		Gson gson = CommonUtil.gson();
		Head head = new Head();
		head.setRequestId(UUID.randomUUID().toString());
		head.setServiceCode(Constants.INSERT_RP);
		head.setIp(userinfo.getCurrentIp());
		head.setUserId(userinfo.getUserId());
		RolePermission r = new RolePermission();
		r.setRoleId(roleId);
		r.setPermissionCode(gson.toJson(codes));
		SocketDTO dto = super.send(head, r);
		Head rHead = dto.getHead();
		if (rHead.getResponseCode().equals(Constants.SUCCESS)) {
			return true;
		}
		return false;
	}

}
